package encaps.action;

import encaps.entities.Grant;
import encaps.entities.Movie;
import encaps.entities.MovieLocal;
import encaps.entities.MovieLocalHome;
import encaps.logging.JMSUtil;
import encaps.logging.Log;
import encaps.resources.Labels;
import encaps.utils.EntityUtil;
import encaps.utils.SystemException;
import encaps.utils.XMLHelper;
import java.util.Date;
import javax.ejb.FinderException;
import javax.ejb.RemoveException;
import javax.naming.NamingException;
import org.jdom.Element;

public class DeleteMovieAction extends Action {

    public static final String DELETE_MOVIE = "deleteMovie";
    private ActionContext actionContext;
    private Long id;

    public DeleteMovieAction(ActionContext context, Grant requiredGrant) {
        this.actionContext = context;
        this.requiredGrant = requiredGrant;
    }

    public Element execute() throws ActionExecutionException {
        try {
            MovieLocalHome movieHome = EntityUtil.getMovieHome();
            id = Long.valueOf(actionContext.getTextParameter(ID));
            MovieLocal movie = movieHome.findByPrimaryKey(id);

            JMSUtil.sendLogMessage(Log.DELETE,
                    EntityUtil.getUserHome().findByLogin(actionContext.getUserLogin()).getID(),
                    actionContext.getUserLogin(), new Date(), Movie.TABLE_NAME,
                    movie.getId(), movie.getTitle());
            movie.remove();
            return XMLHelper.createTextMessage(Labels.getLabel(Labels.MOVIE_DELETED_MESSAGE));
        } catch (FinderException ex) {
            String message = String.format(Labels.getLabel(Labels.MOVIE_NOT_FOUND_MESSAGE_PATTERN), id);
            throw new ActionExecutionException(message, ex);
        } catch (NamingException ex) {
            throw new ActionExecutionException(Labels.getLabel(Labels.CANNOT_FIND_LOCAL_HOME_OBJECT_MESSAGE), ex);
        } catch (RemoveException ex) {
            throw new ActionExecutionException(Labels.getLabel(Labels.REMOVAL_ERROR_MESSAGE), ex);
        } catch (SystemException ex) {
            throw new ActionExecutionException(Labels.getLabel(Labels.CANNOT_EXECUTE_ACTION), ex);
        }
    }
}
